package com.fingard.dsp.bank.directbank.lchs01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextWriter;

import java.net.URLDecoder;
import java.util.Date;


/**
 * 创兴银行-公共方法
 * @author alan
 * @date 2020-05-18
 * @version 1.0
 */
public class LCHS01Base extends DirectBase {

    protected static TransIDHelper idHelper = new TransIDHelper(1, 9999);

    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }

    protected void writeCommonHeader(XmlTextWriter xmlWriter, LCHS01Header p_bankHeader) throws Exception {
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\" ?>");
        xmlWriter.writeStartElement("ifp");
        xmlWriter.writeStartElement("header");
        xmlWriter.writeElementString("transCode", p_bankHeader.trCode, true);//交易码
        xmlWriter.writeElementString("cifMaster", bankFront.org, true);//客户号
        xmlWriter.writeElementString("entSeqNo", p_bankHeader.entSeqNo, true);//企业财务系统流水号
        Date date = new Date();
        xmlWriter.writeElementString("tranDate", Format.Date8Format.format(date));
        xmlWriter.writeElementString("tranTime", Format.Time6Format.format(date));
        xmlWriter.writeElementString("retCode", "",true);
        xmlWriter.writeElementString("entUserId", bankFront.operator);//操作员
        xmlWriter.writeElementCDATA("password", bankFront.userPassword);//操作员密码
        xmlWriter.writeEndElement();
    }

    /**
     * 发送银行前置
     *
     * @param p_reqStr
     * @return
     * @throws Exception
     */
    protected String[] sendToBank(String p_reqStr,String transType,String commandCode) throws Exception {
        //发送银行前置
        String[] retStr = new String[]{"", ""};
        WriteBankUrlLogLn("请求银行的地址" + bankFront.serverURL);
        String reqData="chb_data="+p_reqStr;
        reqData = URLDecoder.decode(reqData, getCharset());
        WriteBankLogStep2(reqData);
        //后置挡板
        if (StringHelper.hasAnyChar(transType) && StringHelper.hasAnyChar(commandCode)) {
            this.detailSimulateForBank(bankFront.bankCode, transType, commandCode, reqData, retStr);
            if (retStr[1].length() > 0) {
                return retStr;
            }
        }
        WebRequest tmpWebRequest = new WebRequest(bankFront.serverURL);
        tmpWebRequest.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
        tmpWebRequest.setRequestProperty("Cache-Control","no-cache");
        tmpWebRequest.setRequestProperty("connection", "Close");
        byte[] tmpToWriteBytes = reqData.getBytes(getCharset());
        retStr = tmpWebRequest.upload(tmpToWriteBytes, getCharset());
        WriteBankLogStep3(retStr[1]);
        return retStr;
    }
}
